﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;
using System.Collections.Generic;
using System.Threading;
public partial class UserManage_UsersList : BasePage
{
    IRolePurviewHandler usersManage = new RolePurviewHandler();
    private static bool isUpdate = false;
    private static bool isDel = false;
    DataBase db = new DataBase();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!strPermission.Contains("1006"))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
                else
                {  //判断用户有没有添加目的地权限
                    if (strPermission.Contains("1007"))
                    {
                        lblUserAdd.Visible = true;
                    }
                    else
                    {
                        lblUserAdd.Visible = false;
                    }
                    //判断用户有没有修改目的地权限
                    if (strPermission.Contains("1008"))
                    {
                        isUpdate = true;
                    }
                    else
                    {
                        isUpdate = false;
                    }
                    //判断用户有没有删除目的地权限
                    if (strPermission.Contains("1009"))
                    {
                        isDel = true;
                    }
                    else
                    {
                        isDel = false;
                    }
                    
                }

               // CheckPagePermission();//判断当前用户有没有添加删除更新的权限

            }
          
            ViewState["OrderBy"] = "UserID";
            ViewState["Accending"] = "asc";
            FillDDl();
            dataBind();
        }
    }


    private void FillDDl()
    {
        string sqlStr = "SELECT S.* FROM Sy_Client as S where S.Status=@Status";
        SqlParameter[] parms=new SqlParameter[1];
        parms[0] = new SqlParameter("@Status", "1");
        DataTable dt =usersManage.GetUsersList(sqlStr,parms);
        ddlCompany.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlCompany.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlCompany.DataTextField = "HKShortName";
        }
        else
        {
            ddlCompany.DataTextField = "CNShortName";
        }
        ddlCompany.DataValueField = "PKID";
        ddlCompany.DataBind();
        ddlCompany.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect,"-1"));
        ddlCompany.Items.Insert(1,new ListItem("special-line","0"));
    }
   

    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string sqlstr, ref SqlParameter[] parms)
    {
        List<SqlParameter> list = new List<SqlParameter>();
        sqlstr = "";
        if (ViewState["Value"] != null)
        {
            if (ViewState["Name"] != null)
            {
                list.Add(new SqlParameter("@ColumnName",ViewState["Value"].ToString()));
                sqlstr += " and " + ViewState["Name"] + " like '%' +  @ColumnName + '%'";
            }
        }
        if (ViewState["Company"] != null)
        {
            list.Add(new SqlParameter("@ClientID",ViewState["Company"].ToString()));
            sqlstr += " and ClientID=@ClientID ";
        }
        parms = list.ToArray();
    }
       


    public string GetRoles(object roleIDs)
    {
        string name = string.Empty;
        DataBase db = new DataBase();
        if (roleIDs.ToString() != string.Empty)
        {
            string sqlStr = "select RoleName from Roles where RoleID in(" + roleIDs.ToString() + ")";
            DataTable dt = db.RunSql(sqlStr);
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (i == dt.Rows.Count - 1)
                    {
                        name += dt.Rows[i]["RoleName"].ToString();
                    }
                    else
                    {
                        name += dt.Rows[i]["RoleName"].ToString() + ",";
                    }
                }
            }
        }
        return name;
    }

    public string GetClient(object client)
    {
        string name = string.Empty;
        ISyClientHandler clientManage = new SyClientHandler();
        Sy_ClientQuery query = clientManage.GetClient(int.Parse(client.ToString()));
        if (query != null)
        {
            if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
            {
                name = query.ENGShortName;
            }
            else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
            {
                name = query.HKShortName;
            }
            else
                name = query.CNShortName;
        }
        if (int.Parse(client.ToString()) == 0)
        {
            name = "special-line";
        }
        return name;

    }

    private void dataBind()
    {
        string sqlStr = "SELECT * FROM Users where 1=1 ";
        SqlParameter[] parms = new SqlParameter[1];
        string clause = string.Empty;
        ProcessParms(ref clause, ref parms);
        sqlStr += clause;

        DataTable dt = usersManage.GetUsersList(sqlStr, parms);
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        gvUserList.DataSource = view;
        gvUserList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotal.Text = "0";
        }
    }
  
    protected void gvUserList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvUserList.PageIndex = e.NewPageIndex;
        dataBind();

    }
    protected void gvUserList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Del")
        {
            if (!usersManage.UserDelete(int.Parse(e.CommandArgument.ToString())))
            {
                Jscript.AlertInAjax(Resources.Messages.DeleteFailed, UpdatePanel1);
            }
        }
        else if (e.CommandName == "Action")
        {
            UsersQuery query = usersManage.GetUsers(int.Parse(e.CommandArgument.ToString()));
            if (query != null)
            {
                if (query.IsActivity == 1)
                {
                    query.IsActivity = 0;
                }
                else
                {
                    query.IsActivity = 1;
                }

                if (!usersManage.UserUpdate(query))
                {
                    Jscript.AlertInAjax(Resources.Messages.UpdateFailed, UpdatePanel1);
                }
            }
        }
        dataBind();

    }
    protected void gvUserList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBind();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (txtloginName.Text != string.Empty)
        {
            ViewState["Value"] = txtloginName.Text.Trim();
            ViewState["Name"] = ddlColumnName.SelectedValue;
        }
        else
        {
            ViewState["Value"] = null;
            ViewState["Name"] = null;
        }
        if (ddlCompany.SelectedValue != "-1")
        {
            ViewState["Company"] = ddlCompany.SelectedValue;
        }
        else
        {
            ViewState["Company"] = null;
        }
        dataBind();
    }

    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvUserList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBind();
    }
    protected void gvUserList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton btnDel = (LinkButton)e.Row.FindControl("lbtnDel");
            Label lblEdit = (Label)e.Row.FindControl("lblUpdate");

            if (isUpdate)
            {
                lblEdit.Visible = true;
            }
            else
            {
                lblEdit.Visible = false;
            }

            if (isDel)
            {
                btnDel.Visible = true;
            }
            else
            {
                btnDel.Visible = false;
            }
        }
    }

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvUserList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvUserList.PageCount)
            {
                this.gvUserList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
        }
    }
}
